package cn.autumnorange.app.common.consumer.gts;

import cn.autumnorange.app.common.consumer.rpc.header.wrapper.HttpServletRequestRPCWrapper;
import cn.autumnorange.app.common.rpc.RPCWrapper;
import com.taobao.txc.common.TxcContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/** @author wsf 对requestHeader设置gts分布式事务id */
@Slf4j
@Component
public class GtsConsumerServiceImpl implements GtsConsumerService {
  @Override
  public String setXidToHeader() {
    HttpServletRequestRPCWrapper httpServletRequestRPCWrapper =
        RPCWrapper.getHttpServletRequestRPCWrapper();
    String xid = TxcContext.getCurrentXid();
    log.info("分布式事务xid创建结果:{}", xid);
    httpServletRequestRPCWrapper.setHeader(GtsConsumerService.XID, xid);
    return xid;
  }

  @Override
  public String removeXidByHeader() {
    HttpServletRequestRPCWrapper httpServletRequestRPCWrapper =
        RPCWrapper.getHttpServletRequestRPCWrapper();
    String xid = httpServletRequestRPCWrapper.getHeader(GtsConsumerService.XID);
    log.info("分布式事务xid请求头移除:{}", xid);
    httpServletRequestRPCWrapper.removeHeader(GtsConsumerService.XID);
    return xid;
  }
}
